package cn.qyd.atomic;

import cn.qyd.common.Person;
import sun.misc.Unsafe;

import java.io.File;
import java.lang.reflect.Field;

/**
 * @author 邱运铎
 * @date 2024-03-24 21:11
 */
public class UnsafeDemo01 {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Unsafe unsafe = getUnsafe();
        Person person = new Person("java", 20);
        long fieldOffset = unsafe.objectFieldOffset(Person.class.getDeclaredField("age"));
        System.out.println("age offset: " + fieldOffset);
        unsafe.putInt(person,fieldOffset,21);
        System.out.println(unsafe.getInt(person,fieldOffset));
        System.out.println(person.getAge());
    }

    public static Unsafe getUnsafe() throws IllegalAccessException, NoSuchFieldException {
        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        //File theUnsafe = Unsafe.class.getDeclaredFields()[0]; //和上面效果一样
        theUnsafe.setAccessible(true);
        Unsafe unsafe = (Unsafe) theUnsafe.get(null);
        return unsafe;
    }
}
